/*
尽可能还原 Promise 中的每一个 API, 并通过注释的方式描述思路和原理.
*/
class MyPromise {
    //函数构造
    //构建更改promise状态的两个函数，pending->resolve，pending->reject
    constructor (executor) {
        executor(this.resolve, this,reject)
    }
    //promise的状态
    status = 'pending'
    //定义成功之后的接受值value
    value = undefined;
    //定义失败之后的返回值reason
    reason = undefined;
    //更改成功状态的函数resolve，更改为fulfilled成功
    resolve = value => {
        //判断当状态为pending的时候才执行修改为fulfilled
        if(this.status != 'pending'){
            return
        }
        this.status = 'fulfilled'
        //成功之后将接收到的value赋值给this.value保存
        this.value = value
    }
    //更改失败状态的函数reject，更改为rejected失败
    reject = reason => {
        //判断当状态为pending的时候才执行修改为rejected
        if(this.status != 'pending'){
            return
        }
        this.status = 'rejected'
        //失败之后将接收到的reason赋值给this.reason保存
        this.reason = reason
    }
    //定义链式调用的then方法
    then(success,failed){
        if(this.status == 'fulfilled'){
            //将保存的value通过success函数传递出去
            success(this.value)
        }else{
            //将保存的reason通过fasiled函数传递出去
            failed(this.reason)
        }
    }
}